package com.sctvcloud.dongqu.ui.activities;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.luck.picture.lib.permissions.RxPermissions;
import com.sctvcloud.dongqu.R;
import com.sctvcloud.dongqu.base.BaseActivity;
import com.sctvcloud.dongqu.utils.ShareUtils;
import com.tencent.rtmp.TXLiveConstants;
import com.tencent.rtmp.TXLivePushConfig;
import com.tencent.rtmp.TXLivePusher;
import com.tencent.rtmp.ui.TXCloudVideoView;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class CameraPusherActivity extends BaseActivity {

    @BindView(R.id.pusher_tx_cloud_view)
    protected TXCloudVideoView mPusherView;

    @BindView(R.id.btn_start)
    protected ImageView btn_start;


    @BindView(R.id.btn_voice)
    protected ImageView btn_voice;

    @BindView(R.id.btn_switch_camera)
    protected ImageView btn_switch_camera;

    @BindView(R.id.btn_tips)
    protected ImageView btn_tips;



    private TXLivePusher mLivePusher;
    private TXLivePushConfig mLivePushConfig;

    // 推流url
    private String bsePushUrl;
    private String pushUrl;

    // 拉流url
    private String basePlayUrl;
    private String playUrl;

    private String urlNO;

    // 鉴权串信息
    private String urlToken;

    // 是否已经推流
    private boolean isPush =false;

    private boolean isMute =false;

    private boolean heng = true;
    private boolean forward=true;
    private Handler handler = new Handler();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setThisImmersive(true);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera_pusher);
        ButterKnife.bind(this);
        initData();

        rxPermissions = new RxPermissions(this);
        onTakePhoto();

    }


    @SuppressLint("ResourceType")
    protected void initView() {

        mLivePushConfig = new TXLivePushConfig();
//        mLivePushConfig.setEnableZoom(true);
//        // 设置噪声抑制
//        mLivePushConfig.enableAEC(true);
//        // 开启硬件加速
//        mLivePushConfig.setHardwareAcceleration(TXLiveConstants.ENCODE_VIDEO_HARDWARE);
//        // 开启 MainProfile 硬编码模式
//        mLivePushConfig.enableVideoHardEncoderMainProfile(true);


        mLivePusher = new TXLivePusher(this);
        mLivePusher.setConfig(mLivePushConfig);

        btn_start.setBackgroundResource(R.mipmap.icon_video_record);
        btn_voice.setBackgroundResource(R.mipmap.live_icon_voice_on);


        mLivePusher.startCameraPreview(mPusherView);


        if(!forward){
            switchCamera();
        }
        if(heng){
            btn_start.setRotation(90f);
            onOrientationChange(false);

            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);

            lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
            lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
            lp.bottomMargin = dpTopx(this,20);
            lp.rightMargin = dpTopx(this,20);

            lp.width = dpTopx(this,30);
            lp.height = dpTopx(this,30);


            btn_voice.setLayoutParams(lp);
            btn_voice.setRotation(90f);


            RelativeLayout.LayoutParams lp2 = new RelativeLayout.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);

            lp2.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
            lp2.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
            lp2.bottomMargin = dpTopx(this,70);
            lp2.rightMargin = dpTopx(this,20);


            lp2.width = dpTopx(this,30);
            lp2.height =  dpTopx(this,30);

            btn_switch_camera.setLayoutParams(lp2);
            btn_switch_camera.setRotation(90f);

            RelativeLayout.LayoutParams lp3 = new RelativeLayout.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);

            lp3.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
            lp3.addRule(RelativeLayout.CENTER_HORIZONTAL);

            lp3.bottomMargin = -dpTopx(this,20);

            btn_tips.setBackgroundResource(R.mipmap.frame_vertical_bg);

        //    lp3.topMargin = dpTopx(this,10);
            btn_tips.setLayoutParams(lp3);
            btn_tips.setRotation(90f);



        }else{
            btn_start.setRotation(0f);
            onOrientationChange(true);

            RelativeLayout.LayoutParams lp3 = new RelativeLayout.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);

            lp3.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
            lp3.addRule(RelativeLayout.CENTER_HORIZONTAL);

            lp3.bottomMargin = dpTopx(this,20);


            btn_tips.setBackgroundResource(R.mipmap.frame_horizontal_bg);
            btn_tips.setLayoutParams(lp3);
            btn_tips.setRotation(0f);

        }



    }


    private int dpTopx(Context context, float dp){
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dp * scale + 0.5f);
    }


    private RxPermissions rxPermissions;

    public void onTakePhoto() {
        // 启动相机拍照,先判断手机是否有拍照权限
        rxPermissions.request(Manifest.permission.CAMERA).subscribe(new Observer<Boolean>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Boolean aBoolean) {
                if (aBoolean) {
                    initView();
                } else {
                    toast(getString(com.luck.picture.lib.R.string.picture_camera));
                    finish();
                }
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }




    protected void initData() {

        pushUrl = ShareUtils.getString(this, "PushDomain", "");
        heng = ShareUtils.getBoolean(this, "heng", true);
        forward = ShareUtils.getBoolean(this, "forward", true);




    }

    /**
     * 开始推流
     */
    private void startPush() {

        isPush = true;

        mLivePusher = new TXLivePusher(this);
        mLivePusher.setConfig(mLivePushConfig);
        mLivePusher.startCameraPreview(mPusherView);


        if(!forward){
            switchCamera();
        }
        if(heng){
            onOrientationChange(false);
        }else{
            onOrientationChange(true);
        }

        int ret = mLivePusher.startPusher(pushUrl.trim());
        i("ret：" + ret);
        if (ret == -5) {
            i("startRTMPPush: license 校验失败");
        }

        i(String.format("拉流地址：%s%s", basePlayUrl, urlNO));

        btn_tips.setVisibility(View.GONE);
    }


    public static void i(String text) {
            Log.i("sakura", text);
    }
    
    
    /**
     * 停止直播
     */
    private void stopPush() {

        mLivePusher.stopPusher();
        // 如果已经启动了摄像头预览，请在结束直播时将其关闭
    //    mLivePusher.stopCameraPreview(true);

        isPush = false;

        toast("已停止直播");

        btn_tips.setVisibility(View.VISIBLE);

    }

    /**
     * 切换摄像头
     */
    private void switchCamera() {

        mLivePusher.switchCamera();

        toast("已切换摄像头");

    }

    /**
     * 横竖屏直播切换
     *
     * @param isPortrait
     */
    private void onOrientationChange(boolean isPortrait) {
        if (isPortrait) {
            mLivePushConfig.setHomeOrientation(TXLiveConstants.VIDEO_ANGLE_HOME_DOWN);
            mLivePusher.setConfig(mLivePushConfig);
            mLivePusher.setRenderRotation(0);
        } else {
            mLivePushConfig.setHomeOrientation(TXLiveConstants.VIDEO_ANGLE_HOME_RIGHT);
            mLivePusher.setConfig(mLivePushConfig);
            // 因为采集旋转了，为了保证本地渲染是正的，则设置渲染角度为90度。
            mLivePusher.setRenderRotation(90);
        }
    }


    @OnClick({R.id.btn_start, R.id.btn_switch_camera,R.id.btn_voice
            })
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_start:
                if(!isPush){
                    toast("开始直播");
                    startPush();
                    btn_start.setBackgroundResource(R.mipmap.icon_video_recording);
                } else{
                    stopPush();
                    btn_start.setBackgroundResource(R.mipmap.icon_video_record);

                }
                break;

            case R.id.btn_switch_camera:
                switchCamera();
                break;
            case R.id.btn_voice:
                if(isMute){
                    btn_voice.setBackgroundResource(R.mipmap.live_icon_voice_on);
                    isMute = false;
                    mLivePusher.setMute(false);
                }else{
                    btn_voice.setBackgroundResource(R.mipmap.live_icon_voice_off);
                    isMute = true;
                    mLivePusher.setMute(true);
                }
                break;
            default:
                break;
        }
    }





    @Override
    protected void onDestroy() {

        stopPush();
        toast("已停止直播");

        super.onDestroy();
    }

}
